package com.example.libretranslatemobile;

import android.os.Handler;
import android.os.Message;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class TranslateProcess {

    private String api_key_libre_translate;
    private String hostLibreTranslate;

    public TranslateProcess(String hostLibreTranslate, String api_key_libre_translate){
        this.api_key_libre_translate = api_key_libre_translate;
        this.hostLibreTranslate = hostLibreTranslate;
    }
    public TranslateProcess(String hostLibreTranslate){
        this.hostLibreTranslate = hostLibreTranslate;
    }

    void translateStart(Handler handler, String source, String target, String field){
        final Gson gson = new GsonBuilder().create();
        final Retrofit retrofit = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create(gson))
                .baseUrl(hostLibreTranslate)
                .build();
        final Link intf = retrofit.create(Link.class);
        new Thread(new Runnable() {
            @Override
            public void run() {
                Map<String, String> mapJson = new HashMap<String, String>();
                if (api_key_libre_translate != null){
                    mapJson.put("api_key", api_key_libre_translate);
                }
                mapJson.put("q", field);
                mapJson.put("source", source);
                mapJson.put("target", target);

                Call<Object> call = intf.translate(mapJson);

                String buffer;
                //handler.sendEmptyMessage(int);

                try {
                    Response<Object> response = call.execute();
                    System.out.println("\n.body =" + response.body() + "\n.toString" + response.toString());

                    Message message = new Message();
                    System.out.println(response.body());
                    if(response.body() == null){
                        message.obj = "Please set your API in\nSetting -> Connections -> and type your api key in field \"You need get API key\"";
                        //message.obj = response;
                    }else {

                        buffer = (String.valueOf(response.body()).split("=")[1]).split("\\}$")[0];
                        System.out.println("LOG: " + buffer);
                        message.obj = buffer;
                    }
                    handler.sendMessage(message);

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }


}
